package chaw.android.train;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.train.MoreActivities.MoreSpecialActivity;
import chaw.android.util.HttpRequestManager;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;

import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class StationListActivity extends ListActivity{
	private ArrayList<JSONObject> json_list;
	private ArrayList<StationItem> list;
	private StationItemAdapter adapter;
	private String station_id, station_name;
	private WebView bannerWebView;
	private ArrayList<String> favorite_list;
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.stationlist);
	    station_id = "";
	    station_name = "";
	    
	    bannerWebView = (WebView) findViewById(R.id.banner);
		bannerWebView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url){
				String[] values = url.split("!");
				if(values[1].equals("app")){
					if(values[2].equals("live")){
						Intent intent = new Intent(getBaseContext(), AllBoardActivity.class);
						startActivity(intent);
						
					}
					else if(values[2].equals("enjoy")){
						Intent intent = new Intent(getBaseContext(), MoreSpecialActivity.class);
						startActivity(intent);
					}
				}
				else if(values[1].equals("board")){
					StationIdAsynkTask task = new StationIdAsynkTask();
					String[] params = new String[]{ ServerURL.stationIdFromBoard, "board_id", values[2]};
					task.execute(params);
				}
				else if(values[1].equals("web")){
					Intent intent = new Intent(Intent.ACTION_VIEW); 
					Uri uri = Uri.parse(values[2]); 
					intent.setData(uri); 
					startActivity(intent);
				}
				return true;
			}
		});
		bannerWebView.loadUrl(ServerURL.bannerWebView(Preferences.getValue(getBaseContext(), "device_token"),
													  Preferences.getValue(getBaseContext(), "user_id"),
													  Preferences.getValue(getBaseContext(), "version")));
		bannerWebView.getSettings().setJavaScriptEnabled(true);
	    favorite_list = new ArrayList<String>();
	}

	private void setListView(){
		list = new ArrayList<StationItem>();
	    json_list = new ArrayList<JSONObject>();
	    list.clear();
	    json_list.clear();
	    
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.stationList, "user_id", Preferences.getValue(getBaseContext(), "user_id")};
		task.execute(params);
	}
	
    private final static Comparator<JSONObject> myComparator= new Comparator<JSONObject>() {
        private final Collator collator = Collator.getInstance();
		@Override
		public int compare(JSONObject object1, JSONObject object2) {
        	try {
				return collator.compare(object1.get("name"), object2.get("name"));
			} catch (JSONException e) {
				e.printStackTrace();
				return 0;
			}
		}
    };

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		StationItem selectedItem = (StationItem) parent.getItemAtPosition(position);
		UploadAsynkTask task = new UploadAsynkTask();
		String[] params ;
		
		if(selectedItem.getIconId() == R.drawable.btn_remove){
			list.get(position).setIconId(R.drawable.btn_add);
			params = new String[]{ ServerURL.deleteFavoriteStation, "user_id", Preferences.getValue(getBaseContext(), "user_id"),
					"station_id", selectedItem.getStationId()};
		}
		else{
			list.get(position).setIconId(R.drawable.btn_remove);
			params = new String[]{ ServerURL.addFavoriteStation, "user_id", Preferences.getValue(getBaseContext(), "user_id"),
					"station_id", selectedItem.getStationId()};
		}
		
		task.execute(params);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
	}
	
	private class StationItemAdapter extends ArrayAdapter<StationItem>{
		private ArrayList<StationItem> items;
		private int layout;
		
		public StationItemAdapter(Context ctx, int rsrcId, ArrayList<StationItem> data){
			super(ctx, rsrcId, data);
			this.items = data;
			this.layout = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(layout, null);
			}
			StationItem e = items.get(position);
			if(e != null){
				if(e.getIconId() == R.drawable.btn_remove){
					((TextView)v.findViewById(R.id.label)).setText(Html.fromHtml("<b>" + e.getStationName() + "</b>"));
				}
				else
					((TextView)v.findViewById(R.id.label)).setText(e.getStationName());
				((ImageView)v.findViewById(R.id.icon)).setImageResource(e.getIconId());
			}
			return v;
		}
	}
	
	private class StationItem{
		private String stationId, stationName;
		private int iconId;
		
		public StationItem(String initId, String initName){
			stationId = initId;
			stationName = initName;
		}

		public String getStationId() {
			return stationId;
		}
		
		public String getStationName() {
			return stationName;
		}
		
		public int getIconId() {
			return iconId;
		}

		public void setIconId(int iconId) {
			this.iconId = iconId;
		}
		
	}
	private class StationIdAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				JSONObject station = new JSONObject(result);
				station_id = station.get("station_id").toString();
				station_name = station.get("station_name").toString();
				String board_id = station.get("board_id").toString();
				Intent intent = new Intent(getBaseContext(), BoardViewActivity.class);
				intent.putExtra("board_id", board_id);
				intent.putExtra("station_id", station_id);
				intent.putExtra("station_name", station_name);
				TrainTravelActivity tab = (TrainTravelActivity) getParent();
		        TrainTravelActivity.tabHost.setCurrentTab(3);
				tab.onTabChanged("Tab4");
				((FavoriteActivity) tab.getCurrentActivity()).startChildActivity("BoardView", intent);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private class UploadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();
		}
	}
	
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			list.clear();
			json_list.clear();
			favorite_list.clear();
			
			try{
				JSONObject json_result = new JSONObject(result);
				JSONArray json_favorite_list = json_result.getJSONArray("favorite_list");
				JSONArray json_station_list = json_result.getJSONArray("station_list");
				
				for(int i = 0 ; i < json_station_list.length(); i++){
					JSONObject json_obj = (JSONObject) json_station_list.get(i);
					json_list.add(json_obj);
				}
				Collections.sort(json_list, myComparator);
				
				for(int i = 0 ; i < json_favorite_list.length(); i++){
					JSONObject json_obj = (JSONObject) json_favorite_list.get(i);
					favorite_list.add(json_obj.getString("station_id"));
				}
				
				for(int i = 0 ; i < json_list.size() ; i++){
					String stationName = (String)json_list.get(i).get("name");
					String stationId = json_list.get(i).get("station_id").toString();
					StationItem eachItem = new StationItem(stationId.toString(), stationName);
					
					if(favorite_list.contains(stationId)){
						eachItem.setIconId(R.drawable.btn_remove);
					}
					else{
						eachItem.setIconId(R.drawable.btn_add);
					}
					list.add(eachItem);
				}
				adapter = new StationItemAdapter(getBaseContext(), R.layout.list_row, list);
			    ListView lv = getListView();
			    lv.setAdapter(adapter);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
}
